<script>
import Vue from 'vue';
import TagEdit from '../tag-edit/index';
function waitCheckBox() {
  return new Promise((resolve) => {
    let searchCondition = Vue.component('ACheckbox');
    if (!searchCondition) {
      return resolve();
    }
    if (
      typeof searchCondition == 'function' &&
      !searchCondition.options &&
      !searchCondition.super
    ) {
      searchCondition = searchCondition();
    }
    if (searchCondition.then) {
      searchCondition.then(resolve);
    } else {
      resolve();
    }
  });
}
const elementResizeDetector = require('element-resize-detector');
const erdResize = elementResizeDetector();
export default {
  name: 'CommonToolbar',
  props: {
    allToolBtns: {
      type: Array,
      default: () => []
    },
    selectedRows: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      // allButtonNotCheck: [],
      showButton: [],
      moreButton: [],
      checkedValue: [],
      defaultValue: []
      // checkButton: [] //复选
    };
  },

  render() {
    const _this = this;
    const renderSubButton = function (button) {
      let subButton = (
        <a-sub-menu disabled={button.disabled || false} key={button.id} title={button.name}>
          {button.subMenu.map((sub) => {
            return sub.subMenu ? (
              renderSubButton(sub)
            ) : (
              <a-menu-item key={sub.id}>{sub.name}</a-menu-item>
            );
          })}
        </a-sub-menu>
      );
      return subButton;
    };

    const renderMoreButton = function () {
      return _this.moreButton.length ? (
        <div ref="moreButton" style="display:inline-block">
          <a-dropdown class="button-margin">
            <a-menu slot="overlay" onClick={_this.buttonClick.bind(_this)}>
              {_this.moreButton.map((button) => {
                return !button.subMenu ? (
                  <a-menu-item disabled={button.disabled || false} key={button.id}>
                    {button.name}
                  </a-menu-item>
                ) : (
                  renderSubButton(button)
                );
              })}
            </a-menu>
            <a-button>
              {_this.$i18n('cap.template.condition.more')}
              <a-icon class="verttical-icon" type="caret-down" />
            </a-button>
          </a-dropdown>
        </div>
      ) : null;
    };
    const renderTip = function (tip) {
      return (
        <div class="tip-container">
          <a-tooltip mouseEnterDelay={0.2}>
            <template slot="title">
              <span>
                {Array.isArray(tip)
                  ? tip.map((item) => {
                    return (
                      <span>
                        {item}
                        <br />
                      </span>
                    );
                  })
                  : tip}
              </span>
            </template>
            <a-icon type="question-circle" />
          </a-tooltip>
        </div>
      );
    };
    const renderMain = function (buttonParent) {
      return (
        <a-dropdown disabled={buttonParent.disabled || false} class="button-margin">
          <a-menu slot="overlay" onClick={_this.buttonClick.bind(buttonParent)}>
            {buttonParent.subMenu.map((button) => {
              return !button.subMenu ? (
                <a-menu-item key={button.id}>{button.name}</a-menu-item>
              ) : (
                renderSubButton(button)
              );
            })}
          </a-menu>
          <a-button
            type={buttonParent.type}
            disabled={buttonParent.disabled || false}
            class={buttonParent.tip ? 'button-has-tip' : ''}>
            {buttonParent.name}
            <a-icon class="verttical-icon" type="caret-down" />
            {buttonParent.tip && renderTip(buttonParent.tip)}
          </a-button>
        </a-dropdown>
      );
    };
    // <i style="font-size: 10px;margin-left: 5px" class="CAP cap-icon-shu-zhankai"></i>
    return (
      <div class="pending-common-toolbar">
        <div class="hidden-buttons" ref="hiddenButton">
          {this.allButtonNotCheck.map((button) => {
            if (button.type === 'tag') {
              return (
                <TagEdit class="button-margin" data={button} selectedRows={this.selectedRows} />
              );
            }
            return (
              <a-config-provider autoInsertSpaceInButton={false}>
                <a-button
                  type={button.type || 'default'}
                  disabled={button.disabled || false}
                  class={button.tip ? 'button-margin button-has-tip' : 'button-margin'}
                  key={button.id}>
                  {button.name}
                  {button.subMenu ? <a-icon class="verttical-icon" type="caret-down" /> : null}
                  {button.icon ? (
                    <i
                      class={[button.icon, 'icon-gap']}
                      style={{ backgroundColor: button.color, lineHeight: '1.6' }}
                    />
                  ) : null}
                  {button.tip && (
                    <div class="tip-container">
                      <a-icon type="question-circle" />
                    </div>
                  )}
                </a-button>
              </a-config-provider>
            );
          })}
        </div>
        <div ref="showToolbar" class="pending-toolbar-conent">
          {this.showButton.map((button) => {
            if (button.type === 'tag')
              return (
                <TagEdit class="button-margin" data={button} selectedRows={this.selectedRows} />
              );
            return button.subMenu ? (
              renderMain(button)
            ) : (
              <a-config-provider autoInsertSpaceInButton={false}>
                <a-button
                  class={button.tip ? 'button-margin button-has-tip' : 'button-margin'}
                  id={'button-' + button.id}
                  type={button.type}
                  disabled={button.disabled || false}
                  onClick={this.buttonClick.bind(_this, button)}>
                  {button.name}
                  {button.icon ? (
                    <i
                      class={[button.icon, 'icon-gap']}
                      style={{ backgroundColor: button.color, lineHeight: '1.6' }}
                    />
                  ) : null}
                  {button.tip && renderTip(button.tip)}
                </a-button>
              </a-config-provider>
            );
          })}
          {renderMoreButton()}
          {this.checkButton.length > 0 ? (
            <div ref="checkButton" style="display: inline-block">
              {this.checkButton.map((checkbox) => {
                return (
                  <a-checkbox
                    defaultChecked={checkbox.checked}
                    title={checkbox.name}
                    onChange={(e) => this.checkOnchange(e, checkbox)}
                    value={checkbox.value}>
                    {checkbox.name}
                  </a-checkbox>
                );
              })}
            </div>
          ) : null}
        </div>
      </div>
    );
  },

  computed: {
    checkButton() {
      return this.allToolBtns.filter((item) => {
        if (item.checked) {
          this.defaultValue.push(item.value);
          // console.log(this.defaultValue, 'this.defaultValue.');
        }
        return item.type === 'checkbox';
      });
    },
    allButtonNotCheck() {
      return this.allToolBtns.filter((item) => {
        if (!item.type || item.type !== 'checkbox') {
          return true;
        }
      });
    }
  },
  watch: {
    allToolBtns: {
      handler: function (newV) {
        console.log('----- allToolBtns -----', newV);
        this.checkedValue = [];
        this.defaultValue = [];
        this.$nextTick(() => {
          // console.log(this.checkButton, 'this.checkButton1');
          this.resize();
        });
      },
      deep: true
    }
  },
  created() { },

  mounted() {
    this.$nextTick(() => {
      waitCheckBox().then(() => {
        erdResize.listenTo(this.$refs.showToolbar, this.resize);
      });
    });
  },

  methods: {
    resize() {
      this.showButton = [];
      this.moreButton = [];
      // console.log(this.$refs.hiddenButton.clientWidth);
      const allButtonsWidth = this.$refs.hiddenButton.clientWidth;
      let showButtonWidth = this.$refs.showToolbar.clientWidth;
      // console.log(showButtonWidth, 'showButtonWidth');
      let checkBoxWidth = this.$refs.checkButton?.clientWidth || 0;
      const allButtons = this.$refs.hiddenButton.getElementsByTagName('button');
      const hasCheckBox = this.checkButton.length > 0;
      if (hasCheckBox) {
        showButtonWidth = showButtonWidth - checkBoxWidth;
      }
      const hasMore = allButtonsWidth > showButtonWidth;
      console.log(allButtonsWidth, showButtonWidth, 'resize');
      let buttonWidth = 0;
      if (hasMore) {
        const moreButtonWidth = this.$refs.moreButton?.clientWidth;
        if (moreButtonWidth) {
          buttonWidth = moreButtonWidth + 8;
        } else {
          buttonWidth = 98;
        }
      }
      // if (hasCheckBox) {
      //   buttonWidth += checkBoxWidth;
      // }
      for (let i = 0; i < allButtons.length; i++) {
        if (this.allButtonNotCheck[i].isVisable) {
          // 必须要显示的按钮的宽度先计算出来
          const currentWidth = allButtons[i].clientWidth;
          buttonWidth += currentWidth + 8;
        }
      }

      for (let i = 0; i < allButtons.length; i++) {
        const currentWidth = allButtons[i].clientWidth;
        if (!this.allButtonNotCheck[i].isVisable) {
          // 必须要显示的按钮的宽度不再重复计算
          buttonWidth += currentWidth + 8;
        }

        let needMoreWidth = buttonWidth;
        if (needMoreWidth <= showButtonWidth || this.allButtonNotCheck[i].isVisable) {
          this.showButton.push(this.allButtonNotCheck[i]);
        } else {
          this.moreButton.push(this.allButtonNotCheck[i]);
        }
      }
      // console.log(this.showButton, 'showButton');
      // console.log(this.moreButton, 'moreButton');
    },

    buttonClick(e) {
      // console.log('click', e);
      const buttonKey = e.id || e.key;
      this.$emit('buttonClick', buttonKey);
    },
    checkOnchange(e, checkBox) {
      const returnValue = {
        id: checkBox.id,
        checked: e.target.checked
      };
      this.$emit('checkOnchange', returnValue);
    }
  },

  beforeDestroy() {
    erdResize.uninstall(this.$refs.showToolbar);
  }
};
</script>

<style lang="scss" scoped>
.pending-common-toolbar {
  position: relative;
  width: 100%;
  overflow: hidden;
  text-align: left;
  // display: flex;

  .hidden-buttons {
    opacity: 0;
    z-index: -1;
    position: absolute;
    white-space: nowrap;
    display: flex;
  }

  .button-margin {
    margin-right: 8px;
    border-radius: 2px;
  }

  .button-has-tip {
    padding-right: 11px;
  }

  .pending-toolbar-conent {
    width: 100%;
    min-width: 100%;
    white-space: nowrap;
    align-items: center;
    display: flex;
  }

  ::v-deep .ant-dropdown-menu-item-disabled:hover {
    background-color: #fff !important;
  }

  .icon-gap {
    color: #fff;
    margin-left: 4px;
    vertical-align: middle;
    width: 16px;
    height: 16px;
    font-size: 10px;
    border-radius: 50%;
    margin-top: -1px;
  }

  .verttical-icon {
    vertical-align: middle;
  }

  .tip-container {
    margin-left: 10px;
    padding-left: 10px;
    height: 100%;
    line-height: 28px;
    display: inline-block;
    border-left: 1px solid #d9d9d9;
  }
}
</style>
